#!/usr/bin/env bash
# Copyright (c) 2023-2025 Tigera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# Enable job control so that background processes get their own process groups.
set -m

my_dir="$(dirname $0)"
repo_dir="$my_dir/../.."

# shellcheck source=../../felix/.semaphore/batches.sh
source "$repo_dir/$COMPONENT/.semaphore/batches.sh"

log_monitor_regexps=(
  "(?<!Decode)Failure"
  "SUCCESS"
  "Parallel test node"
  "Test batch"
  "FV-TEST-START"
  "^test.*\.\.\. ok"
  "\.\.\. ERROR$"
  "Failure output:"
  "^ERROR:"
  "^Traceback"
  "^FAILED"
  "^OK$"
  "^XML:"
  "^\[success\]"
  "^\[error\]"
  "RUNNER:"
)

# Combine the regexps; in Perl mode, grep only supports one
# pattern so we combine them with '|'.
monitor_pattern=""
for r in "${log_monitor_regexps[@]}"; do
  monitor_pattern="${monitor_pattern}|$r"
done
monitor_pattern="${monitor_pattern:1}" # Strip leading '|'

vm_name_prefix=$1
artifacts_dir="$repo_dir/artifacts"

echo
echo "===== Starting tests ====="
echo

pids=()
monitor_pids=()
log_files=()
for batch in "${batches[@]}"; do
  vm_name="$vm_name_prefix$batch"
  log_file="$artifacts_dir/test-$batch.log"
  touch "$log_file"

  (run_batch "$my_dir/on-test-vm" $batch $vm_name $log_file) &
  pid=$!

  log_files+=( $log_file )
  pids+=( $pid )

  prefix="[batch=${batch}]"
  echo "$prefix Started test batch in background with PID=$pid; monitoring its log ($log_file)."
  (
    # Redirect tail's stdin from /dev/null to prevent waiting
    # forever on reads in semaphore CI
    tail -F $log_file < /dev/null | \
      grep --line-buffered --perl "${monitor_pattern}" -B 2 -A 15 | \
      sed 's/.*/'"${prefix}"' &/' | \
      grep --perl --line-buffered -v '^\[batch=[^\]]+\]\s+$';
  ) &
  mon_pid=$!
  monitor_pids+=( $mon_pid )
done

final_result=0

echo
echo "===== Waiting for background test runners to finish ===="
echo

summary=()
for i in "${!batches[@]}"; do
  batch=${batches[$i]}
  pid=${pids[$i]}
  echo "Waiting for test batch $batch to finish (PID=$pid)..."
  if wait "$pid"; then
    summary+=( "Test batch $batch SUCCEEDED" )
    echo "===== Test batch $batch SUCCEEDED (PID=$pid).  Log file will be uploaded as artifact ${log_files[$i]}. ====="
  else
    summary+=( "Test batch $batch FAILED; Log file will be uploaded as artifact ${log_files[$i]}" )
    echo "===== Test batch $batch FAILED (PID=$pid).  Log file will be uploaded as artifact ${log_files[$i]}. ====="
    final_result=1
  fi
done

echo
echo "===== Shutting down test monitors ====="
for pid in "${monitor_pids[@]}"; do
  # Note: negative PID to kill the entire process group.
  kill -TERM -$pid || true
done

echo "===== Results summary ====="
for s in "${summary[@]}"; do
  echo "  $s"
done
echo

echo "===== Done, exiting with RC=$final_result ====="

exit $final_result
